<?php

/*
 * Copyright (C) 2009 - 2011 Pham Cong Dinh
 *
 * This file is part of Spica.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

/**
 * This class provides simple mechanism to encode and decode a base-62 number.
 *
 * @category   spica
 * @package    core
 * @subpackage crypto
 * @author     Pham Cong Dinh <pcdinh at phpvietnam dot net>
 * @since      Version 0.3
 * @since      May 14, 2010
 * @copyright  Pham Cong Dinh (http://www.phpvietnam.net)
 * @license    http://www.gnu.org/licenses/lgpl-3.0.txt
 * @version    $Id: Crypto.php 1775 2010-04-26 10:24:21Z pcdinh $
 */
class SpicaBase62
{
    /**
     * Encodes a number.
     *
     * @param string $number
     * @return string
     */
    public static function encode($number)
    {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        // For 32 bit OS
        // can't handle numbers larger than 2^31-1 = 2147483647
        $str = '';
        
        do
        {
            $i = $number % 62;
            $str = $chars[$i] . $str;
            $number = ($number - $i) / 62;
        } while ($number > 0);
        
        return $str;
    }

    /**
     * Decodes a string.
     *
     * @param string $str
     * @return string
     */
    public static function decode($str)
    {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        
        $len = strlen($str);
        $number = 0;
        $arr = array_flip(str_split($chars));

        for ($i = 0; $i < $len; ++$i)
        {
            $number += $arr[$str[$i]] * pow(62, $len - $i - 1);
        }

        return $number;
    }
}

?>